<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      python/其他/02-MySQL主从搭建基于docker | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>python/其他/02-MySQL主从搭建基于docker</h2>



  <p class="post-date">2019-12-29</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="10分钟搭建MySQL主从同步（基于docker"><a href="#10分钟搭建MySQL主从同步（基于docker" class="headerlink" title="10分钟搭建MySQL主从同步（基于docker)"></a>10分钟搭建MySQL主从同步（基于docker)</h1><h2 id="一-主从配置原理"><a href="#一-主从配置原理" class="headerlink" title="一 主从配置原理"></a>一 主从配置原理</h2><p><img src="https://tva1.sinaimg.cn/large/006y8mN6gy1g8mcd6efcdj31q10u01kx.jpg" alt="image-20191104214516600"></p>
<p>mysql主从配置的流程大体如图：</p>
<p>1）master会将变动记录到二进制日志里面；</p>
<p>2）master有一个I/O线程将二进制日志发送到slave;</p>
<p>3) slave有一个I/O线程把master发送的二进制写入到relay日志里面；</p>
<p>4）slave有一个SQL线程，按照relay日志处理slave的数据；</p>
<h2 id="二-操作步骤"><a href="#二-操作步骤" class="headerlink" title="二 操作步骤"></a>二 操作步骤</h2><h3 id="2-1我们准备两台装好mysql的服务器（我在此用docker模拟了两台机器）"><a href="#2-1我们准备两台装好mysql的服务器（我在此用docker模拟了两台机器）" class="headerlink" title="2.1我们准备两台装好mysql的服务器（我在此用docker模拟了两台机器）"></a>2.1我们准备两台装好mysql的服务器（我在此用docker模拟了两台机器）</h3><table>
<thead>
<tr>
<th>环境</th>
<th>mysql版本</th>
<th align="right">ip地址:端口号</th>
</tr>
</thead>
<tbody><tr>
<td>主库（master）</td>
<td>5.7</td>
<td align="right">172.16.209.100:33307</td>
</tr>
<tr>
<td>从库（slave）</td>
<td>5.7</td>
<td align="right">172.16.209.100:33306</td>
</tr>
</tbody></table>
<p>用docker拉起两个mysql容器，步骤如下（对docker不熟悉的同学可以查看docker快速入门章节）：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 拉取mysql5.7镜像</span></span><br><span class="line">docker pull mysql:<span class="number">5.7</span></span><br><span class="line"><span class="comment">#在home目录下创建mysql文件夹，下面创建data和conf.d文件夹</span></span><br><span class="line">mkdir /home/mysql</span><br><span class="line">mkdir /home/mysql/conf.d</span><br><span class="line">mkdir /home/mysql/data/</span><br><span class="line"> </span><br><span class="line">创建my.cnf配置文件</span><br><span class="line">touch /home/mysql/my.cnf</span><br><span class="line"></span><br><span class="line">mkdir /home/mysql2</span><br><span class="line">mkdir /home/mysql2/conf.d</span><br><span class="line">mkdir /home/mysql2/data/</span><br><span class="line">touch /home/mysql2/my.cnf</span><br><span class="line">my.cnf添加如下内容：</span><br><span class="line">[mysqld]</span><br><span class="line">user=mysql</span><br><span class="line">character-set-server=utf8</span><br><span class="line">default_authentication_plugin=mysql_native_password</span><br><span class="line">secure_file_priv=/var/lib/mysql</span><br><span class="line">expire_logs_days=<span class="number">7</span></span><br><span class="line">sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION</span><br><span class="line">max_connections=<span class="number">1000</span></span><br><span class="line"><span class="comment">##主库----start--- 同一局域网内注意要唯一</span></span><br><span class="line">server-id=<span class="number">100</span>  </span><br><span class="line"><span class="comment">## 开启二进制日志功能，可以随便取（关键）</span></span><br><span class="line">log-bin=mysql-bin</span><br><span class="line"><span class="comment">##主库----end--- </span></span><br><span class="line"></span><br><span class="line"><span class="comment">##从库----start--- </span></span><br><span class="line"><span class="comment">## 设置server_id,注意要唯一</span></span><br><span class="line">server-id=<span class="number">101</span>  </span><br><span class="line"><span class="comment">## 开启二进制日志功能，以备Slave作为其它Slave的Master时使用</span></span><br><span class="line">log-bin=mysql-slave-bin   </span><br><span class="line"><span class="comment">## relay_log配置中继日志</span></span><br><span class="line">relay_log=edu-mysql-relay-bin </span><br><span class="line"><span class="comment">##从库----end--- </span></span><br><span class="line"></span><br><span class="line">[client]</span><br><span class="line">default-character-set=utf8</span><br><span class="line"></span><br><span class="line">[mysql]</span><br><span class="line">default-character-set=utf8</span><br><span class="line"><span class="comment">#启动主库容器（挂载外部目录，端口映射成33307，密码设置为123456）</span></span><br><span class="line">docker run  -di -v /home/mysql/data/:/var/lib/mysql -v /home/mysql/conf.d:/etc/mysql/conf.d -v /home/mysql/my.cnf:/etc/mysql/my.cnf -p <span class="number">33307</span>:<span class="number">3306</span> --name mysql-master -e MYSQL_ROOT_PASSWORD=<span class="number">123456</span> mysql:<span class="number">5.7</span></span><br><span class="line"><span class="comment">#启动从库容器（挂载外部目录，端口映射成33306，密码设置为123456）</span></span><br><span class="line">docker run  -di -v /home/mysql2/data/:/var/lib/mysql -v /home/mysql2/conf.d:/etc/mysql/conf.d -v /home/mysql2/my.cnf:/etc/mysql/my.cnf -p <span class="number">33306</span>:<span class="number">3306</span> --name mysql-slave -e MYSQL_ROOT_PASSWORD=<span class="number">123456</span> mysql:<span class="number">5.7</span></span><br></pre></td></tr></table></figure>

<h2 id="2-2-远程连接入主库和从库"><a href="#2-2-远程连接入主库和从库" class="headerlink" title="2.2 远程连接入主库和从库"></a>2.2 远程连接入主库和从库</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">#连接主库</span><br><span class="line">mysql -h 172.16.209.100 -P 33307 -u root -p123456</span><br><span class="line">#在主库创建用户并授权</span><br><span class="line">##创建test用户</span><br><span class="line">create user &#39;test&#39;@&#39;%&#39; identified by &#39;123&#39;;</span><br><span class="line">##授权用户</span><br><span class="line">grant all privileges on *.* to &#39;test&#39;@&#39;%&#39; ;</span><br><span class="line">###刷新权限</span><br><span class="line">flush privileges;</span><br><span class="line">#查看主服务器状态(显示如下图)</span><br><span class="line">show master status;</span><br></pre></td></tr></table></figure>

<p><img src="https://tva1.sinaimg.cn/large/006y8mN6gy1g8mvq2x880j30ys0620ux.jpg" alt="image-20191105085514111"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">#连接从库</span><br><span class="line">mysql -h 172.16.209.100 -P 33306 -u root -p123456</span><br><span class="line">#配置详解</span><br><span class="line">&#x2F;*</span><br><span class="line">change master to </span><br><span class="line">master_host&#x3D;&#39;MySQL主服务器IP地址&#39;, </span><br><span class="line">master_user&#x3D;&#39;之前在MySQL主服务器上面创建的用户名&#39;， </span><br><span class="line">master_password&#x3D;&#39;之前创建的密码&#39;, </span><br><span class="line">master_log_file&#x3D;&#39;MySQL主服务器状态中的二进制文件名&#39;, </span><br><span class="line">master_log_pos&#x3D;&#39;MySQL主服务器状态中的position值&#39;;</span><br><span class="line">*&#x2F;</span><br><span class="line">#命令如下</span><br><span class="line">change master to master_host&#x3D;&#39;101.133.225.166&#39;,master_port&#x3D;33307,master_user&#x3D;&#39;test&#39;,master_password&#x3D;&#39;123&#39;,master_log_file&#x3D;&#39;mysql-bin.000003&#39;,master_log_pos&#x3D;0;</span><br><span class="line">#启用从库</span><br><span class="line">start slave;</span><br><span class="line">#查看从库状态（如下图）</span><br><span class="line">show slave status\G;</span><br></pre></td></tr></table></figure>

<p><img src="https://tva1.sinaimg.cn/large/006y8mN6gy1g8mvvzo3xzj30u00u5keo.jpg" alt="image-20191105090050611"></p>
<p>##2.3 测试主从同步</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">#在主库上创建数据库test1</span><br><span class="line">create database test1;</span><br><span class="line">use test1;</span><br><span class="line">#创建表</span><br><span class="line">create table tom (id int not null,name varchar(100)not null ,age tinyint);</span><br><span class="line">#插入数据</span><br><span class="line">insert tom (id,name,age) values(1,&#39;xxx&#39;,20),(2,&#39;yyy&#39;,7),(3,&#39;zzz&#39;,23);</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">#在从库上查看是否同步成功</span><br><span class="line">#查看数据库</span><br><span class="line">show database;</span><br><span class="line">use test1;</span><br><span class="line">#查看表</span><br><span class="line">show tables;</span><br><span class="line">#查看数据</span><br><span class="line">select * from test1;</span><br></pre></td></tr></table></figure>

<p>可以看到大功告成</p>
</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/db/Redis%E7%B3%BB%E5%88%97/04-Redis%E7%B3%BB%E5%88%97%E4%B9%8B-%E6%8C%81%E4%B9%85%E5%8C%96/">
        <span class="nav-arrow">← </span>
        
          db/Redis系列/04-Redis系列之-持久化
        
      </a>
    
    
      <a class="nav-right" href="/db/Redis%E7%B3%BB%E5%88%97/05-Redis%E7%B3%BB%E5%88%97%E4%B9%8B-%E4%BD%BF%E7%94%A8%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98/">
        
          db/Redis系列/05-Redis系列之-使用常见问题
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#10分钟搭建MySQL主从同步（基于docker"><span class="toc-nav-text">10分钟搭建MySQL主从同步（基于docker)</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#一-主从配置原理"><span class="toc-nav-text">一 主从配置原理</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#二-操作步骤"><span class="toc-nav-text">二 操作步骤</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-1我们准备两台装好mysql的服务器（我在此用docker模拟了两台机器）"><span class="toc-nav-text">2.1我们准备两台装好mysql的服务器（我在此用docker模拟了两台机器）</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-2-远程连接入主库和从库"><span class="toc-nav-text">2.2 远程连接入主库和从库</span></a></li></ol></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/python/其他/02-MySQL主从搭建基于docker/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "python/其他/02-MySQL主从搭建基于docker",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>